import React, { useState } from "react"
import { Tabs } from "antd-mobile"
import { SearchOutline, UnorderedListOutline } from "antd-mobile-icons"
import "./index.scss"
import { getChannels, toggleTab } from "../../store/actions/home"

import { useDispatch, useSelector } from "react-redux"
import Articles from "./Articles"
import { useHistory } from "react-router-dom"
import { Popup } from "antd-mobile"
import PopupModel from "../../components/PopupModel"
import { getAllChannels } from "../../store/actions"
function Home() {
  const dispatch = useDispatch()
  const history = useHistory()
  const channelActiveKey = useSelector((state) => state.home.channelActiveKey)
  // 弹出层
  const [visible, setVisible] = useState(false)
  // tab切换
  const changeTab = (key) => {
    dispatch(toggleTab(+key))
  }

  // 获取我的频道
  const channels = JSON.parse(localStorage.getItem("my_channel")) || []
  dispatch(getAllChannels())
  if (channels.length === 0) {
    // 获取我的频道
    dispatch(getChannels())
    // 获取可选频道列表
  }
  return (
    <div className="main">
      {channels.length > 0 && (
        <Tabs
          className="tabs"
          activeLineMode="fixed"
          activeKey={channelActiveKey + ""}
          onChange={changeTab}
        >
          {channels?.map((item) => {
            return (
              <Tabs.Tab forceRender title={item.name} key={item.id}>
                {item.id === channelActiveKey && <Articles id={item.id} />}
              </Tabs.Tab>
            )
          })}
        </Tabs>
      )}
      <div className="bar_btn">
        <span
          onClick={() => {
            history.push("/search")
          }}
        >
          <SearchOutline />
        </span>
        <span
          onClick={() => {
            setVisible(true)
          }}
        >
          <UnorderedListOutline />
        </span>
        <Popup visible={visible} position="left" bodyStyle={{ width: "100%" }}>
          <PopupModel
            cloneModel={() => {
              setVisible(false)
            }}
          />
        </Popup>
      </div>
    </div>
  )
}

export default Home
